package com.slkj.shilixiaoyuanapp.ui.main;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.LazyFragment;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.MainShowZsEntity;
import com.slkj.shilixiaoyuanapp.entity.MainShowUiEntity;
import com.slkj.shilixiaoyuanapp.entity.MessageNoticeListEntity;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.NewsWebActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.WebActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.main.message.MessageNoticeListActivity;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.notice.NoticeDetailActivity;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.notice.NoticeDetailActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.util.ListUtils;
import com.slkj.shilixiaoyuanapp.view.MySwipeRefreshLayout;
import com.slkj.shilixiaoyuanapp.view.StateLayout;
import com.slkj.shilixiaoyuanapp.view.UPMarqueeView;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;

/**
 * Created  on 2018-07-15
 *
 * @author 唐开阔
 * @describe 首页展示fragment
 */
public class ShowFragment extends LazyFragment implements SwipeRefreshLayout.OnRefreshListener{
    @BindView(R.id.banner)
    MZBannerView banner;
    @BindView(R.id.recycer)
    RecyclerView recycerType;
    @BindView(R.id.recycerTj)
    RecyclerView recycerTj;
    @BindView(R.id.upview)
    UPMarqueeView upMarqueeView;
    @BindView(R.id.refresh)
    MySwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.statelayout)
    StateLayout stateLayout;
    @BindView(R.id.view_upview)
    View upMarqueeViewParent;
    int[] drawbles = {R.drawable.ic_sxpd, R.drawable.ic_xysp, R.drawable.ic_sxjk, R.drawable.ic_yssy, R.drawable.ic_shsj, R.drawable.ic_xwxg};
    List<String> images = new ArrayList<>();
    List<MainShowZsEntity> typeEntityList = new ArrayList<>();
    List<MainShowUiEntity.MainShowTjEntity> tjEntityList = new ArrayList<>();
    @BindArray(R.array.main_show_type)
    String[] typeItems;
    @BindView(R.id.imgSm)
    ImageView imgSm;
    static String baseUrl;
    static {
        boolean isZhxx =  UserRequest.getInstance().getUser().isZhxx();
        baseUrl = isZhxx ? "http://120.178.185.196:8082/zhongheAPP/index.html#!/":"http://47.106.8.136:8082/school/demo/index.html#!/";
    }
    String[] urls = {"Character","Academic","MentalHealth","Art","practice","BehavioralHabit"};
    private static final int SPAN_COUNT = 3;
    BaseQuickAdapter typeAdapter;
    BaseQuickAdapter tjAdapter;
    List<View> views = new ArrayList<>();

    @Override
    protected int getResId() {
        return R.layout.fragment_show;
    }

    @Override
    protected void onRealLoaded() {
        swipeRefreshLayout.setOnRefreshListener(this);
        imgSm.setOnClickListener(v -> {

        });
        stateLayout.setOnReLoadListener(this::onRefresh);
        recycerTj.setLayoutManager(new LinearLayoutManager(getContext()));
        recycerType.setLayoutManager(new GridLayoutManager(getContext(), SPAN_COUNT));
        typeAdapter = new BaseQuickAdapter<MainShowZsEntity, BaseViewHolder>(R.layout.item_main_show_type, typeEntityList) {
            @Override
            protected void convert(BaseViewHolder helper, final MainShowZsEntity item) {
                helper.setText(R.id.tv_name, item.getName())
                        .setImageResource(R.id.img, drawbles[helper.getAdapterPosition()])
                        .itemView
                        .setOnClickListener(v ->
                                WebActivity__JumpCenter.builder(getActivity())
                                .setUrl(item.getUrl())
                                .setTitle(item.getName())
                                .setPosition(helper.getAdapterPosition())
                                .create().go());

            }
        };
        tjAdapter = new BaseQuickAdapter<MainShowUiEntity.MainShowTjEntity, BaseViewHolder>(R.layout.item_main_show_tj, tjEntityList) {
            @Override
            protected void convert(BaseViewHolder helper, final MainShowUiEntity.MainShowTjEntity item) {
                Glide.with(getContext()).load(item.getHeadPath()).into((ImageView) helper.getView(R.id.img));
                helper.setText(R.id.content,item.getHeadBody());
                helper.setText(R.id.title,item.getTitle());
                helper.itemView.setOnClickListener(v ->
                        NewsWebActivity__JumpCenter.builder(getContext())
                        .setUrl(item.getUrl())
                                .setTitle(item.getTitle())
                        .create()
                        .go());
            }
        };
        for (int i = 0; i < typeItems.length; i++) {
            typeEntityList.add(new MainShowZsEntity(typeItems[i],baseUrl+urls[i]));
        }
        recycerTj.setAdapter(tjAdapter);
        recycerType.setAdapter(typeAdapter);
        onRefresh();
    }



    @Override
    public void onRefresh() {
        HttpHeper.get().mainPageService()
                .getShowData()
                .compose(bindToLifecycle())
                .compose(getThread())
                .subscribe(new CommonCallBack<MainShowUiEntity>() {
                    @Override
                    public void onCallBackSuccess(MainShowUiEntity data) {
                        swipeRefreshLayout.setRefreshing(false);
                        stateLayout.showContentView();
                        setViewData(data);
                    }

                    @Override
                    public void onFail(String mes) {
                        stateLayout.showErrorView();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    /**
     * 给view设置数据
     * @param data
     */
    private void setViewData(MainShowUiEntity data) {
        images.clear();
        images.addAll(data.getSowingmap());
        banner.setPages(images, (MZHolderCreator<BannerViewHolder>) () -> new BannerViewHolder());
        banner.start();
        views.clear();
        tjEntityList.clear();
        tjEntityList.addAll(data.getInfoemation());
        tjAdapter.notifyDataSetChanged();
        if(ListUtils.isEmpty(data.getClassNotice()) && ListUtils.isEmpty(data.getSchoolNotice())){
            upMarqueeViewParent.setVisibility(View.GONE);
        }else {
            List<MessageNoticeListEntity.NoticeEntity> noticeEntityList = new ArrayList<>();
            if (!ListUtils.isEmpty(data.getClassNotice())){
                noticeEntityList.addAll(data.getClassNotice());
            }
            if (!ListUtils.isEmpty(data.getSchoolNotice())){
                noticeEntityList.addAll(data.getSchoolNotice());
            }
            for(MessageNoticeListEntity.NoticeEntity entity:noticeEntityList){
                //设置滚动的单个布局
                LinearLayout moreView = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_main_show_tz, null);
                //初始化布局的控件
                TextView tv1 = (TextView) moreView.findViewById(R.id.tv_type);
                TextView tv2 = (TextView) moreView.findViewById(R.id.tv_title);
                //进行对控件赋值
                tv2.setText(entity.getBody());
                tv1.setText(entity.getType()==1?"班级":"学校");
                //添加到循环滚动数组里面去
                views.add(moreView);
            }
            upMarqueeViewParent.setVisibility(View.VISIBLE);
            upMarqueeView.setViews(views);
            /**
             * 设置item_view的监听
             */
            upMarqueeView.setOnItemClickListener(new UPMarqueeView.OnItemClickListener() {
                @Override
                public void onItemClick(int position, View view) {
                    NoticeDetailActivity__JumpCenter.builder(getActivity())
                            .setId(noticeEntityList.get(position).getId())
                            .setType(NoticeDetailActivity.TYPE_MESSAGE)
                            .create().go();
                }
            });
        }

    }

//    @Override
//    public void onPause() {
//        super.onPause();
//        banner.pause();//暂停轮播
//    }
//
//    @Override
//    public void onResume() {
//        super.onResume();
//        banner.start();//开始轮播
//    }


    @Override
    public void onDestroyView() {
        if (banner!=null)
        banner.pause();

        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public static class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.layout_banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            Glide.with(context).load(data).into(mImageView);
        }
    }
}
